﻿using System;
using System.Net;
using System.Diagnostics;

namespace UnionnetClient.Model
{
	public class LoginSourceGetter
	{
		public event EventHandler<GetLoginSourceCompletedEventArgs> GetLoginSourceCompleted;

		public LoginSourceGetter()
		{
			wc.Timeout = 15000;

			wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
			{
				if (GetLoginSourceCompleted != null)
				{
					try
					{
						if (ValidateSoure(e.Result))
						{
							GetLoginSourceCompleted(this, new GetLoginSourceCompletedEventArgs(true, e.Result));
						}
						else
						{
							GetLoginSourceCompleted(this, new GetLoginSourceCompletedEventArgs(false));
						}
					}
					catch(Exception ex)
					{
						Debug.WriteLine("[APP][ERR] " + ex.Message);
						Debug.WriteLineIf(ex.InnerException != null, "[APP][ERR] " + ex.InnerException.Message);
						GetLoginSourceCompleted(this, new GetLoginSourceCompletedEventArgs(false));
					}
				}
			};
		}

		public void GetLoginSourceAsync()
		{
			wc.DownloadStringAsync(remoteAddress[new Random().Next(remoteAddress.Length - 1)]);
		}

		#region private

		private Roovent.Network.WebClientWithTimeoutLite wc = new Roovent.Network.WebClientWithTimeoutLite();

		private string[] remoteAddress = new string[]{
			"http://1.2.3.4",
			"http://www.baidu.com",
			"http://1.2.3.4",
			"http://www.sina.com",
			"http://1.2.3.4",
			"http://www.qq.com",
			"http://1.2.3.4",
			"http://www.renren.com",
		};

		private bool ValidateSoure(string content)
		{
			return content.Contains("form") && content.Contains("vpn") && content.Contains("uid");
		}

		#endregion
	}
}
